package com.naodong.shenluntiku.mvp.view.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.naodong.shenluntiku.R;
import com.naodong.shenluntiku.di.component.DaggerMineComponent;
import com.naodong.shenluntiku.di.module.MineModule;
import com.naodong.shenluntiku.mvp.contract.MineContract;
import com.naodong.shenluntiku.mvp.model.bean.UserInfo;
import com.naodong.shenluntiku.mvp.model.data.manager.UserInfoManager;
import com.naodong.shenluntiku.mvp.presenter.MinePresenter;
import com.naodong.shenluntiku.mvp.view.activity.CollectActivity;
import com.naodong.shenluntiku.mvp.view.activity.CropActivity;
import com.naodong.shenluntiku.mvp.view.activity.FeedbackActivity;
import com.naodong.shenluntiku.mvp.view.activity.GetVerCodeActivityAutoBundle;
import com.naodong.shenluntiku.mvp.view.activity.NoticeSetActivity;
import com.naodong.shenluntiku.mvp.view.activity.SubjectHistoryActivity;
import com.naodong.shenluntiku.mvp.view.activity.SubjectWrongActivity;
import com.naodong.shenluntiku.mvp.view.widget.BottomSheetListView;
import com.naodong.shenluntiku.mvp.view.widget.MaterialDialog;
import com.naodong.shenluntiku.util.AppUtil;
import com.naodong.shenluntiku.util.ImageLoaderUtil;
import com.theartofdev.edmodo.cropper.CropImage;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.shingohu.man.base.BaseMVPFragment;
import me.shingohu.man.di.component.AppComponent;
import me.shingohu.man.util.ToastUtil;
import me.shingohu.man.util.ViewUtil;
import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by hujie on 17/4/18.
 */

public class MineFragment extends BaseMVPFragment<MinePresenter> implements MineContract.View {


    @BindView(R.id.nameET)
    TextView nameET;

    @BindView(R.id.headIV)
    ImageView headIV;


    public static SupportFragment getInstance() {
        return new MineFragment();
    }


    @Override
    protected int layoutId() {
        return R.layout.f_mine;
    }


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMineComponent.builder().appComponent(appComponent).mineModule(new MineModule(this)).build().inject(this);
    }

    @Override
    protected void onViewCreated(Bundle savedInstanceState) {
        initView();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        mPresenter.requestUserInfo();
    }

    private void initView() {

        if (UserInfoManager.getInstance().getUserInfo() != null) {
            nameET.setText(UserInfoManager.getInstance().getUserInfo().getNickname());
            ImageLoaderUtil.loadImage(getContext(), UserInfoManager.getInstance().getUserInfo().getAvatar(), headIV);
        }
    }


    @Override
    protected void gc() {

        super.gc();
    }

    @OnClick(R.id.editNameView)
    public void onEditNameView() {


        View view = LayoutInflater.from(getContext()).inflate(R.layout.input_name, null);

        EditText inputET = (EditText) view.findViewById(R.id.inputTV);
        MaterialDialog dialog = new MaterialDialog(getContext());
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setPositiveButton("确定", v -> {
            if (!ViewUtil.isTextEmpty(inputET)) {
                mPresenter.requestEditUserName(ViewUtil.getText(inputET));
            }
            dialog.dismiss();
        });
        dialog.setNegativeButton("取消");
        dialog.setTitle("设置昵称");
        dialog.setOnDismissListener(dialog1 -> KeyboardUtils.hideSoftInput(inputET));
        dialog.show();
        inputET.postDelayed(() -> KeyboardUtils.showSoftInput(inputET), 200);

    }

    @OnClick(R.id.feedbackView)
    public void onFeedbackClick() {
        Intent intent = new Intent(mActivity, FeedbackActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.collectView)
    public void onCollectViewClick() {
        Intent intent = new Intent(mActivity, CollectActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.subjectHistoryView)
    public void onSubjectHistoryViewClick() {
        Intent intent = new Intent(mActivity, SubjectHistoryActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.subjectWrongView)
    public void onSubjectWrongViewClick() {
        Intent intent = new Intent(mActivity, SubjectWrongActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.exitView)
    public void onExitClick() {
        startActivity(GetVerCodeActivityAutoBundle.builder().relogin(true).build(getContext()));
    }

    
    @OnClick(R.id.noticeView)
    public void onDXTXClick() {
        Intent intent = new Intent(mActivity, NoticeSetActivity.class);
        startActivity(intent);
    }

    @Override
    public void showMessage(String msg) {
        ToastUtil.makeToast(msg);
    }

    @Override
    public void onRequesrStart() {
        progressHudUtil.showProgressHud();
    }

    @Override
    public void onRequestFinish() {
        progressHudUtil.dismissProgressHud();
    }

    @Override
    public void onEditUserName(String newUserName) {
        nameET.setText(newUserName);
        UserInfoManager.getInstance().setNickName(newUserName);
    }

    @Override
    public void onUserInfo(UserInfo userInfo) {


        nameET.setText(userInfo.getNickname());
        if (UserInfoManager.getInstance().getUserInfo() != null && userInfo.getAvatar() != null && userInfo.getRelativeAvatar() != null) {
            String newAvatar = userInfo.getRelativeAvatar();
            String oldAvatar = UserInfoManager.getInstance().getUserInfo().getRelativeAvatar();
            if (!newAvatar.equals(oldAvatar)) {
                ImageLoaderUtil.loadImage(getContext(), userInfo.getAvatar(), headIV);
            }
        } else {
            ImageLoaderUtil.loadImage(getContext(), userInfo.getAvatar(), headIV);
        }
    }

    @Override
    public void onEditUserAvatar(String absAavtar, String avatar) {
        ToastUtil.makeToast("头像上传成功");
        UserInfo userInfo = UserInfoManager.getInstance().getUserInfo();
        userInfo.setAvatar(avatar);
        userInfo.setRelativeAvatar(absAavtar);
        UserInfoManager.getInstance().saveUserInfo(userInfo);
        ImageLoaderUtil.loadImage(getContext(), avatar, headIV);
        AppUtil.clearCacheImage(getContext());
    }

    @OnClick(R.id.headIV)
    public void onHeadClick() {

        BottomSheetListView bottomSheetListView = new BottomSheetListView(mActivity);
        bottomSheetListView.setOtherButtonTitles("相册", "拍照");
        bottomSheetListView.setListener(new BottomSheetListView.SimpleBottomSheetListener() {
            @Override
            public void onOtherButtonClick(String result, int index) {
                if (index == 0) {
                    PictureSelector.create(MineFragment.this).openGallery(PictureMimeType.ofImage()).selectionMode(PictureConfig.SINGLE).forResult(PictureConfig.CHOOSE_REQUEST);
                } else {
                    PictureSelector.create(MineFragment.this).openCamera(PictureMimeType.ofImage()).forResult(PictureConfig.CHOOSE_REQUEST);
                }
            }
        });
        bottomSheetListView.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                if (data != null) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    CropImage.activity(Uri.fromFile(new File(selectList.get(0).getPath()))).setAspectRatio(1, 1).setFixAspectRatio(true).start(getContext(), MineFragment.this, CropActivity.class);
                    getActivity().overridePendingTransition(0, 0);
                }
            }
        }
        //裁剪回调
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                Uri resultUri = result.getUri();
                uploadImage(resultUri);
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                ToastUtil.makeToast("图片裁剪出错,请重试");
                AppUtil.clearCacheImage(getContext());
            } else if (resultCode == RESULT_CANCELED) {
                AppUtil.clearCacheImage(getContext());
            }
        }

    }

    private void uploadImage(Uri uri) {
        mPresenter.requestEditUserAvatar(uri.getPath());
    }
}
